

# 未定义的异常 NameError: name 'j' is not defined
#i = j

# 不能赋值的异常 TypeError: 'str' object does not support item assignment
# a = '123'
# a[2] = '0'

# 索引越界的异常 IndexError: string index out of range
# a = '123'
# print(a[3])

# 找不到key的异常 KeyError: 'c'
# d = {'a':1, 'b':2}
# print(d['c'])

# value类型不匹配的异常，如果输入a  ValueError: invalid literal for int() with base 10: 'a'
# y = int(input('please input year: '))

# 找不到属性的异常 AttributeError: 'int' object has no attribute 'append'
# i = 123
# i.append()

# 0不能做除数的异常 ZeroDivisionError: division by zero
#1/0

# 捕获处理异常
# try:
#     y = int(input('please input year: '))
# #except (ValueError, AttributeError, KeyError) as e:
# except Exception as e:
#     print('year must be int!!!! %s ' % e)


# 定义自定义异常
class MyCustomException(RuntimeError):
    def __init__(self, arg):
        self.args = arg


# 抛出自定义异常
try:
    raise MyCustomException('hi')
except MyCustomException as e:
    print("MyCustomException:  %s" % e)


# 一个示例
try:
    file = open('file.txt')
    # 如果open发生异常，下面不会走
    print('open file success!')
    print('parse file.......')
    file.close()
    print('close file finally!')
except FileNotFoundError as e:
    print('%s ' % e)
except PermissionError as e:
    print('%s ' % e)
finally:
    # 如果打开文件失败，则file未定义，所以应该把close放到try里面
    # file.close()
    # 总是会执行
    print('nothing to do in finally here!')

